<!--  -->
<template>
  <div class="concent">
    <div class="map-body">
      <div class="map-operate-box">
        <div class="operate-box">
          <div class="operate-item" v-if="mapPath.length > 1" @click="goBack">
            <img src="/static/images/map-go-back.png" />
          </div>

          <div class="operate-item">
            <img src="/static/images/map-max.png" v-if="echartOption.geo.zoom < 20" @click="zoomBtn('add')" />

            <img src="/static/images/map-max-disabled.png" v-else />
          </div>
          <div class="operate-item">
            <img src="/static/images/map-min.png" v-if="echartOption.geo.zoom > 1" @click="zoomBtn('minus')" />

            <img src="/static/images/map-min-disabled.png" v-else />
          </div>
        </div>
      </div>

      <div class="left-container">
        <div class="myecharts">
          <div :style="{ height: '100%', width: '100%' }" ref="myEchart"></div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  // import * as echarts from 'echarts';
  import echarts from 'echarts';
  import Api from '../../api/assetsMap';
  import cityMap from '../../config/cityMap';
  import provinceMap from '../../config/provinceMap';
  import { getMenuList } from '@/api';
  export default {
    components: {},
    data() {
      return {
        activeIndex: 1,
        echartOption: {
          animationDuration: 700,
          animationEasing: 'cubicOut',
          animationDurationUpdate: 700,
          tooltip: {},
          // 地图样式
          geo: {
            layoutSize: '120%', //地图大小
            layoutCenter: ['50%', '50%'], //0-横向偏移量 1-竖向偏移量
            scaleLimit: {
              min: 1,
              max: 20,
            },
            map: 'china',
            zoom: 1,
            roam: true,

            left: 0,
            right: 0,
            label: {
              sohw: true,
              normal: {
                show: true,
                textStyle: {
                  color: '#999',
                },
              },
              emphasis: {
                color: '#F79100',
              },
            },
            itemStyle: {
              normal: {
                areaColor: '#f1f1f1',
                borderColor: '#fff',
              },
              emphasis: {
                areaColor: '#f0f0f0',
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowBlur: 20,
                borderWidth: 0,
                shadowColor: 'rgba(0, 0, 0, 0.1)',
              },
            },
            regions: [],
          },

          series: [
            {
              type: 'effectScatter',
              legendHoverLink: true,
              effectType: 'ripple',
              showEffectOn: 'render',
              coordinateSystem: 'geo',
              data: [],
              symbol: 'circle',
              symbolSize: 15,
              rippleEffect: {
                period: 4,
                scale: 2.5,
                brushType: 'stroke',
              },
              itemStyle: {
                color: '#F79100',
              },
              tooltip: {
                show: true,
                trigger: 'item',
                showContent: true,
                showDelay: 0,
                hideDelay: 100,
                enterable: true,
                renderMode: '',
                textStyle: {
                  color: 'rgba(0, 0, 0, 0.8)',
                },
                backgroundColor: 'rgba(0, 0, 0, 0.1)',
                formatter: '{b}',
              },
            },
          ],
        },
        myChart: null,
        mapPath: ['china'],
        allData: [],
        basicData: null,
        serviceData: null,
        equipmentData: null,
        levelList: ['china', 'province', 'city'],
        nowLevel: 'china',
        areaColors: ['#0d50d6', '#0841af', '#2281cf'],
        zoom: 1,
        Route: {},
      };
    },
    watch: {
      Route: {
        immediate: false,
        deep: true,
        handler(val) {
          this.goArea();
        },
      },
    },
    destroyed() {
      if (this.dataTimer) {
        clearTimeout(this.dataTimer);
      }
    },
    filters: {
      thousandth(value) {
        return Number(value)
          .toFixed(2)
          .replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
      },
      thousandthInteger(value) {
        var reg = /\d{1,3}(?=(\d{3})+$)/g;
        return (value + '').replace(reg, '$&,');
      },
    },
    async mounted() {
      await this.projectList();
    },
    methods: {
      async projectList() {
        let provinceCodeList = [];
        const { rows } = await Api.projectData({});
        rows.forEach(item => {
          provinceCodeList.push(item.provinceCode);
          this.allData.push({
            mapName: item.provinceName,
            name: item.name,
            value: [Number(item.longitude), Number(item.latitude)],
            code: item.primaryKey,
            spaceKey: item.spaceKey,
          });
        });
        let repetArr = [...new Set(provinceCodeList)];
        if (repetArr.length == 1) {
          this.Route = { cityName:  rows[0].provinceName};
        }
        this.drawECharts();
      },
      async drawECharts() {
        this.myChart = echarts.init(this.$refs.myEchart);
        window.onresize = this.myChart.resize;

        this.goArea();

        this.myChart.on('click', params => {
          this.clickHandel(params);
        });
      },
      setRouter() {
        if (this.mapPath.length == 1) {
          this.Route = {};
        } else {
          this.Route = { cityName: this.mapPath.slice(1).join(',') };
        }
      },
      async clickHandel(params) {
        console.log(params, 'params');
        if (params.name in provinceMap) {
          // 更新路径
          this.mapPath.push(params.name);
          // 如果点击的是34个省、市、自治区，绘制选中地区的二级地图
          this.setRouter();
        } else if (params.name in cityMap) {
          // 更新路径
          this.mapPath.push(params.name);

          this.setRouter();
        } else if (params.componentSubType == 'effectScatter') {
          // 跳转项目页面
          // let code = params.data.code;
          // let pointNum = params.data.pointNum;

          // // 如果在一个城市下数量多于3个，则点击放大地图
          // if (pointNum >= 3 && this.myChart.getOption().geo[0].zoom < 20) {
          //   this.echartOption.geo.zoom = 20;
          //   this.echartOption.geo.center = params.data.value;
          //   this.myChart.setOption(this.echartOption, true);
          //   return;
          // }

          if (!params.data.type) {
            this.mapPath.push(params.data.mapName);
            // 如果点击的是34个省、市、自治区，绘制选中地区的二级地图
            this.setRouter();
            return;
          }

          this.handleView({
            projectKey: params.data.code,
            spaceKey: params.data.spaceKey,
          });
        }
      },
      async handleView(data) {
        let res = await getMenuList({
          parentId: this.$route.query.tabId,
        });

        let menuUrl = res.rows[0].menuUrl;
        let separator = menuUrl.indexOf('?') > -1 ? '&' : '?';
        let queryData = {
          ...data,
          isRefresh: true,
          parentMenuId: this.$route.query.tabId,
          menuId: res.rows[0].primaryKey,
          noTab: true,
        };

        let paramData = [];
        for (let key in queryData) {
          paramData.push(key + '=' + queryData[key]);
        }

        let href = menuUrl + separator + paramData.join('&');
        // console.log(href, 'href')
        window.open(href);
      },
      async goToArea(type = 'china', name = 'china') {
        let data = null;
        if (type == 'province') {
          data = await Api.getProvinceMapJson({ jsonName: provinceMap[name] });
          this.nowLevel = 'province';
        } else if (type == 'city') {
          data = await Api.getCityMapJson({ jsonName: cityMap[name] });
          this.nowLevel = 'city';
        } else {
          data = await Api.getChinaMapJson();
          this.nowLevel = 'china';
        }

        await this.getData();

        let regions = [];

        echarts.registerMap(name, data);
        this.echartOption.geo.map = name;
        this.echartOption.geo.regions = regions;
        this.echartOption.geo.center = null;
        this.echartOption.geo.zoom = 1;

        this.myChart.setOption(this.echartOption, true);
      },
      async getData() {
        let name = this.mapPath[this.mapPath.length - 1];
        if (this.nowLevel == 'province') {
          await this.getSpotList('province', name);
        } else if (this.nowLevel == 'city') {
          await this.getSpotList('city', name);
        } else {
          await this.getSpotList();
        }

        // 清除之前的轮询，重新轮询
        if (this.dataTimer) {
          clearTimeout(this.dataTimer);
        }

        this.dataTimer = setTimeout(() => {
          this.getData();
        }, 180000);
      },
      async getSpotList(type = '', name = '') {
        var data = {};
        if (type) {
          if (type == 'province') {
            data.province = name;
          } else if (type == 'city') {
            data.city = name;
          }
        }
        this.allData.forEach(item => {
          item.type = type;
        });

        var data = [];

        if (!type) {
          data = this.allData;
        } else if (type == 'province') {
          data = this.allData.filter(item => {
            return item.mapName == name;
          });
        }
        this.echartOption.series[0].data = data;
      },
      goArea() {
        if (this.Route.cityName) {
          let nameList = this.Route.cityName.split(',');
          let length = nameList.length;
          let cityName = nameList[length - 1];

          this.mapPath = ['china'].concat(nameList);

          if (cityName in provinceMap) {
            this.goToArea('province', cityName);
          } else if (cityName in cityMap) {
            this.goToArea('city', cityName);
          }
        } else {
          this.mapPath = ['china'];

          this.goToArea();
        }
      },
      async goBack() {
        this.mapPath.pop();
        this.setRouter();
      },
      zoomBtn(type) {
        if (type == 'minus' && this.echartOption.geo.zoom == 1) {
          return;
        }

        if (type == 'add' && this.echartOption.geo.zoom == 20) {
          return;
        }

        if (type == 'minus') {
          this.echartOption.geo.zoom = Math.max(1, this.echartOption.geo.zoom - 2);
        } else if (type == 'add') {
          this.echartOption.geo.zoom = Math.min(20, this.echartOption.geo.zoom + 2);
        }

        if (this.echartOption.geo.zoom == 1) {
          this.echartOption.geo.center = null;
        }

        this.myChart.setOption(this.echartOption, true);
      },
    },
  };
</script>
<style scoped lang="scss">
  /* @import url(); 引入css类 */
  .main {
    width: 100%;
    padding: 0;
  }
  .myecharts {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .map-body {
    height: 100%;
    width: 100%;

    .map-operate-box {
      position: fixed;
      top: 60px;
      right: 30px;
      z-index: 100;
      display: flex;
      margin-top: 6px;

      .operate-box {
        display: flex;
        .operate-item {
          cursor: pointer;
          width: 36px;
          height: 36px;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #919295;
          border: 1px solid #eff5f9;
          box-shadow: 0 0 1px 0 #d9dbe1;
          border-radius: 2px;

          img {
            width: 18px;
            height: 18px;
          }
        }
        .operate-item:nth-child(2) {
          border-top: none;
        }
      }
    }

    .left-container {
      flex: 1;
      height: 100%;
      position: relative;
    }

    .right-container {
      width: 530px;
      height: 100%;
      display: flex;
      align-items: center;
      position: absolute;
      right: 0;
      top: 0;
      overflow: auto;
      z-index: 2;

      .left-main {
        width: 130px;

        .circle-box {
          width: 86px;
          height: 86px;
          position: relative;
          display: flex;
          justify-content: center;
          align-items: center;
          margin: 60px auto 60px 0;
          cursor: pointer;

          .circle {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            background-image: linear-gradient(-180deg, #0d73ca 0%, #0043b8 100%);
            position: relative;
            font-family: PingFangSC-Medium;
            font-size: 12px;
            color: #dae9ff;
            text-align: justify;
            text-align: center;

            img {
              margin: 12px auto 2px;
              width: 28px;
              height: 28px;
            }
          }

          .active {
            position: absolute;
            top: 0;
            left: 0;
            width: 86px;
            height: 86px;
            border-radius: 50%;
            opacity: 0.18;
            background-image: linear-gradient(-180deg, #5ff8ff 0%, #1590d2 100%);
          }
        }

        .active-box {
          .circle {
            background-image: linear-gradient(-180deg, #5ff8ff 0%, #1590d2 100%);
            color: #ffffff;
          }
        }

        .left-27 {
          margin-left: 27px;
        }
      }

      .right-main {
        .content-item {
          padding: 10px;
          border: 1px solid transparent;

          .item-wrap {
            display: flex;
            align-items: flex-end;
            margin-bottom: 12px;

            .content-title {
              display: inline-block;
              margin-right: 20px;
              font-size: 14px;
              color: #ffffff;
              margin-bottom: 5px;
            }

            .content-text {
              margin-right: 20px;

              font-family: BritannicBold;
              font-size: 30px;
              color: #5ef5fe;

              span {
                opacity: 0.8;
                font-family: PingFangSC-Regular;
                font-size: 14px;
                color: #ffffff;
                margin-left: 12px;
              }
            }
          }

          .basic {
            .content-title {
              font-family: PingFangSC-Semibold;
            }
          }

          .project {
            .content-title {
              width: auto;
              margin-right: 20px;
            }
          }
        }
      }
    }
  }
  .concent {
    height: calc(100vh - 100px);
  }
</style>
